#from authkit import permissions
from decorator import decorator
from pylons import request, session
from pylons.helpers import redirect_to
from bumblebee import model as model

def get_user():
    if 'current_user' not in request.environ:
        user_id = session.get('current_user_id')
        if user_id:
            user = model.User.get_by(id = user_id, active = True)
            request.environ['current_user'] = user
        else:
            request.environ['current_user'] = None
    return request.environ['current_user']

def signin(user):
    session['current_user_id'] = str(user.id)
    session.save()

def signout():
    session.pop('current_user_id', None)
    session.save()

def redirect_to_login():
    #TODO: save form params, current url to session
    redirect_to(controller='/login')

def authorize(permission):
    def validate(func, self, *args, **kw):
        try:
            permission.check()
            return func(self, *args, **kw)
        except NotAuthorized:
            redirect_to_login()
    return decorator(validate)

class NotAuthorized(Exception):pass

##### Permission classes #####

class SignedIn(object):

    def check(self):
        if not get_user(): 
            raise NotAuthorized

class InGroup(object):

    def __init__(self, group_name):
        self.group_name = group_name 

    def check(self):
        group = model.Group.get_by(name = self.group_name, active = True)
        if not group or not get_user() in group.members:
            raise NotAuthorized

class HasPermission(object):

    def __init__(self, permission):
        self.permission = permission

    def check(self):
        user = get_user()
        if not user or not user.has_permission(self.permission):
            raise NotAuthorized

